package com.briup.run.web.filter;

import com.briup.run.bean.Memberinfo;
import com.briup.run.constant.CreditConstant;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @Auther: vanse(lc))
 * @Date: 2022/10/10-10-10-9:58
 * @Description：权限控制过滤器: 拦截所有资源
 * 判断对方有无登录 将来可以精确控制
 *          数据库: 记录用户可以访问的资源  并自定义注解控制 @

 */
@WebFilter("/member/*")
//@WebFilter("/*")
public class ControllerAccessFilter implements Filter {
    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
        HttpSession session = request.getSession();
        // 根据memberinfo是否登录过
        Memberinfo memberinfo = (Memberinfo) session.getAttribute("memberinfo");
        String uri = request.getRequestURI();// /run/login.jsp
        if (memberinfo != null ||
                uri.endsWith(CreditConstant.LOGIN_JSP) ||
                uri.endsWith("register.jsp") ||
                uri.endsWith("authImage") ||
                uri.startsWith("/run/images") ||
                uri.startsWith("/run/js") ||
                uri.startsWith("/run/style")
        ) {
            // 如果登录 放行
            // 非敏感资源 放行
            chain.doFilter(req, resp);
        }else{
            session.setAttribute("error","请登录");
            // 如果未登录 拦截
            response.sendRedirect(request.getContextPath()+"/login.jsp");
        }

    }

    public void init(FilterConfig config) throws ServletException {

    }

}
